<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/24 0024
 * Time: 10:17
 */

namespace app\api\service;


use app\service\AliyunOss;
use app\service\BaseService;
use think\Db;
use think\Exception;

class UserService extends BaseService
{
    private $appcode = '02c9e96dfcbf47b3a1935425a0dc86b2';
    private $akId = "LTAI4FtKEfbCr1BQzEuDX1T2";
    private $akSecret = "z9rEkBsLNVd1uj2cO3tad0RDSeAde2";

    /**
     * @name 邀请信息
     * @author zay
     * @Date 2020/3/24 0024 10:17
     */
    public function invite($appdata, $userinfo)
    {
        $uid = $userinfo['id'];
        //$list = Db('user')->field('id,uname,is_effect,nicename')->where("FIND_IN_SET({$uid},tpath)")->select();
        $list = Db('user')->field('id,uname,is_effect,nicename,regtime')->where(['tid' => $uid])->order('regtime','desc')->select();
        //$effect_num = Db('user')->field('count(id) as count')->where("FIND_IN_SET({$uid},tpath)")->where(['is_effect' => 1])->find();
        $effect_num = Db('user')->field('count(id) as count')->where(['tid' => $uid])->where(['is_effect' => 1])->find();
        $effect_num = !empty($effect_num['count']) ? $effect_num['count'] : 0;
        //赠送币数
        $send_coin = Db('invite_reward_coin')->field('sum(coin) as coin')->where(['uid' => $userinfo['id']])->find();
        foreach ($list as $k => &$v) {
            $v['regtime'] = date('Y-m-d', $v['regtime']);
        }
        $data = [
            'total' => count($list),
            'effect_num' => $effect_num,
            'send_coin' => $send_coin ? $send_coin['coin'] : 0,
            'list' => $list
        ];
        apifasong(['zt' => 1, 'msg' => '', 'data' => $data]);
    }

    /**
     * @param $file 身份证图片url
     * @param $side
     * @throws \Exception
     * @internal param $识别身份证
     * @author zay
     * @Date 2020/3/28 0028 16:33
     */

    public function get_code($file, $side)
    {
        $host = "https://ocridcard.market.alicloudapi.com";
        $path = "/idCardAuto";
        $method = "POST";
        $appcode = $this->appcode;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $bodys = "image=" . $file;
        //或者base64
        //$bodys = 'image=data:image/jpeg;base64,......'';  //jpg图片base64
        //$bodys = 'image=data:image/png;base64,......'';   //png图片base64
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        //curl_setopt($curl, CURLOPT_HEADER, true);   如不输出json, 请打开这行代码，打印调试头部状态码。
        //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $out_put = curl_exec($curl);
        $data = json_decode($out_put, true);
        if (!isset($data['code']) || !isset($data['result']['code'])) {
            throw new \Exception('网络错误');
        }
        $code = $data['result']['code'];
        var_dump($code);
    }

    /**
     * @name 验证身份证号
     * @author zay
     * @Date 2020/3/28 0028 16:21
     * @throws \Exception 识别不准
     */
    public function verify($code, $truename)
    {
        $host = "https://gameid.market.alicloudapi.com";
        $path = "/idcheck/forgame";
        $method = "GET";
        $appcode = $this->appcode;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = 'cardNo=' . $code . '&realName=' . urlencode($truename);
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $data = curl_exec($curl);
        $data = json_decode($data, true);
        if (!(isset($data['error_code']) && $data['error_code'] == 0)) {
            throw new \Exception('网络错误');
        }
        if (!(isset($data['result']['isok']) && $data['result']['isok'] == true)) {
            throw new \Exception('验证失败');
        }
        var_dump($data);
        exit;
    }

    /**
     * @name 识别图片中的文字
     * @author zay
     * @Date 2020/3/28 0028 17:21
     * @param $file 本地服务器图片
     * @throws Exception
     * @throws \Exception
     * @return array
     */
    public function get_info($file)
    {
        $url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
        $appcode = $this->appcode;
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        $config = array(
            "side" => "face"
        );
        if ($fp = fopen($file, "rb", 0)) {
            //$binary = fread($fp, filesize($file)); // 文件读取
            $binary = file_get_contents($file); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
        if ($is_old_format == TRUE) {
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );

            if (count($config) > 0) {
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        } else {
            $request = array(
                "image" => "$base64"
            );
            if (count($config) > 0) {
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //var_dump($rbody);exit;
        if ($httpCode != 200) {
            throw new \Exception('网络异常');
        }
        if ($is_old_format) {
            $output = json_decode($rbody, true);
            $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
        } else {
            $result_str = $rbody;
        }
        $data = json_decode($result_str, true);
        if (!isset($data['success'])) {
            throw new Exception('身份证识别异常');
        }
        $res = [
            'name' => $data['name'],
            'num' => $data['num'],
            'sex' => $data['sex'],
            'address' => $data['address'],
            'birth' => $data['birth'],
        ];
        return $res;
    }

    /**
     * @param $img1
     * @param $img2
     * @return mixed
     * @throws \Exception
     * @internal param $人脸对比
     * @author zay
     * @Date date
     */
    public function facechick($img1, $img2)
    {
        //2张人脸对比结果
        $akId = $this->akId;
        $akSecret = $this->akSecret;
        //更新api信息
        $url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";
        /*$img1 = dirname(dirname(dirname(dirname(__FILE__)))) . '/public/image/11.png';
         $img2 = dirname(dirname(dirname(dirname(__FILE__)))) . '/public/image/11.png';*/
        $img1 = config('OSS_PREFIX') . $img1;
        $img2 = config('OSS_PREFIX'). $img2;
        $data = [
            /*'type' => 0,
            'image_url_1' => 'https://china-idc.co/image/333.jpg',
            'image_url_2' => 'https://china-idc.co/image/444.jpg',*/
            'type' => 1,
            'content_1' => $this->base64EncodeImage($img1),
            'content_2' => $this->base64EncodeImage($img2)
        ];
        $options = array(
            'http' => array(
                'header' => array(
                    'accept' => "application/json",
                    'content-type' => "application/json",
                    'date' => gmdate("D, d M Y H:i:s \G\M\T"),
                    'authorization' => '',
                ),
                'method' => "POST", //可以是 GET, POST, DELETE, PUT
                'content' => json_encode($data) //如有数据，请用json_encode()进行编码
            )
        );
        $http = $options['http'];
        $header = $http['header'];
        $urlObj = parse_url($url);

        if (empty($urlObj["query"])) {
            $path = $urlObj["path"];
        } else {
            $path = $urlObj["path"] . "?" . $urlObj["query"];
        }

        $body = $http['content'];
        if (empty($body)) {
            $bodymd5 = $body;
        } else {
            $bodymd5 = base64_encode(md5($body, true));
        }
        $stringToSign = $http['method'] . "\n" . $header['accept'] . "\n" . $bodymd5 . "\n" . $header['content-type'] . "\n" . $header['date'] . "\n" . $path;
        $signature = base64_encode(
            hash_hmac(
                "sha1",
                $stringToSign,
                $akSecret, true));
        $authHeader = "Dataplus " . "$akId" . ":" . "$signature";
        $options['http']['header']['authorization'] = $authHeader;
        $result = $this->http($url, $options['http']['content'], $options['http']['header'], 1);
        if (!isset($result['errno']) || $result['errno'] != 0) {
            throw new \Exception('识别异常');
        }
        return $result;
    }

    /**
     * @name 认证
     * @author zay
     * @Date 2020/4/1 0001 13:28
     */

    public function face_very($appdata, $userinfo)
    {
        DB::startTrans();
        try {
            if ($userinfo['shiming'] == 1) {
                throw new \Exception('你已通过实人认证，无需重复认证!');
            }
            $file = request()->file('file');
            if (!$file) {
                throw new \Exception('图片不完整');
            }
            //获取用户实名信息
            $shiming_info = Db('shiming')->where(['uid' => $userinfo['id']])->find();
            if (empty($shiming_info) || empty($shiming_info['sfz1'])) {
                throw new \Exception('请先去验证身份证');
            }
            if ($shiming_info['zt'] == 1) {
                throw new \Exception('你已通过实人认证，无需重复认证');
            }
            /*$filename = 'shouchi';
            $ret = uploadimg($file, 'image/shiming', $userinfo['uname'] . '_' . $filename, 2000);
            if (!$ret['zt']) {
                apifasong(['zt' => '0', 'msg' => $ret['error']]);
            }*/
            $filename = 'shouchi';
            $oss_data = [
                'file_dir'=>'image/shiming',
                'file_name'=>$userinfo['uname'] . '_' . $filename
            ];
            $ret = AliyunOss::service()->setParam($oss_data)->upload();
            if(!isset($ret['sql_path'])){
                throw new \Exception('图片上传失败');
            }
            //根据身份证获取身份证信息
            $sfz_result = $this->facechick($ret['sql_path'], $shiming_info['sfz1']);
            //验证用户是否已经有身份证信息
            if ($sfz_result['confidence'] <= 65 || $sfz_result['confidence'] >= 98) {
                throw new \Exception('认证不通过');
            }
            $res = DB('shiming')->where(['id' => $shiming_info['id']])->update(['zt' => 3, 'shouchi' => $ret['sql_path']]);
            if (!$res) {
                throw new \Exception('状态更新失败');
            }
            $res1 = Db('user')->where(['id' => $userinfo['id']])->update(['update_time' => time(), 'truename' => $shiming_info['truename']]);
            if (!$res1) {
                throw new \Exception('信息更新失败');
            }
            DB::commit();
            apifasong(['zt' => 1, 'msg' => '认证通过,估计审核需要两个小时']);
        } catch (\Exception $e) {
            DB::rollback();
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 认证
     * @author zay
     * @Date 2020/4/1 0001 13:28
     */

    public function renzheng($appdata, $userinfo)
    {
        try {
            if ($userinfo['shiming'] == 1) {
                throw new \Exception('你已通过实人认证，无需重复认证!');
            }
            $file = request()->file('file');
            if (!$file) {
                throw new \Exception('图片不完整');
            }
            /*$filename = 'sfz1';

            $ret = uploadimg($file, 'image/shiming', $userinfo['uname'] . '_' . $filename, 2000);*/
            $filename = 'sfz1';
            $oss_data = [
                'file_dir'=>'image/shiming',
                'file_name'=>$userinfo['uname'] . '_' . $filename
            ];
            $ret = AliyunOss::service()->setParam($oss_data)->upload();
            if (!$ret['zt']) {
                throw new \Exception($ret['error']);
            }
            //$image_url = dirname(dirname(dirname(dirname(__FILE__)))) . '/public/' . $ret['sql_path'];
            $image_url =config('OSS_PREFIX') . $ret['sql_path'];
            //根据身份证获取身份证信息
            $sfz_info = $this->get_info($image_url);
            //判断年龄
            $birth = substr($sfz_info['birth'], 0, 4);
            $now_year = date('Y');
            $setting = setting();
            if ($now_year - $birth < $setting['age_min'] || $now_year - $birth > $setting['age_max']) {
                throw new \Exception('此年龄不被允许认证');
            }
            //验证身份证是否使用过 如果使用过就不能在使用
            $is_num = Db('shiming')->where(['sfz' => $sfz_info['num']])->find();
            if ($is_num && $is_num['uid'] != $userinfo['id']) {
                throw new \Exception('此身份已认证');
            }
            //验证用户是否已经有身份证信息
            $shiming_info = Db('shiming')->where(['uid' => $userinfo['id']])->find();
            $data['sfz1'] = $ret['sql_path'];
            $data['uid'] = $userinfo['id'];
            $data['uname'] = $userinfo['uname'];
            $data['sex'] = 0;
            if ($sfz_info['sex'] == '男') {
                $data['sex'] = 1;
            } elseif ($sfz_info['sex'] == '女') {
                $data['sex'] = 2;
            }
            $data['truename'] = $sfz_info['name'];
            $data['sfz'] = $sfz_info['num'];
            $data['address'] = $sfz_info['address'];
            $data['time'] = time();
            if (empty($shiming_info)) {
                $res = Db('shiming')->insert($data);
            } else {
                $res = Db('shiming')->where(['uid' => $userinfo['id']])->update($data);
            }
            if (!$res) {
                throw new \Exception('添加实名记录失败');
            }
            apifasong(['zt' => 1, 'msg' => '身份证验证成功']);
        } catch (\Exception $e) {
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 绑定微信、支付宝
     * @author zay
     * @Date 2020/4/7 0007 10:01
     */

    public function bind($appdata, $userinfo)
    {
        try {
            $account_num = $appdata['account_num'];
            //$account = $appdata['account'];
            $code = isset($appdata['code']) ? $appdata['code'] : '';
            $bank = isset($appdata['bank']) ? $appdata['bank'] : '';
            $type = $appdata['type'];//1支付宝 2微信
            if (!in_array($type, [1, 2, 3])) {
                throw new \Exception('类型错误');
            }
            if ($userinfo['shiming'] != 1) {
                throw new \Exception('该用户未实名，不能绑定');
            }
            if ($type == 1 && empty($code)) {
                throw new \Exception('二维码不能为空');
            }
            if ($type == 3 && empty($bank)) {
                throw new \Exception('开户行必填');
            }
            if (empty($account_num)) {
                throw new \Exception('账号必填');
            }
            //查询是否有绑定信息
            $info = db('bank')->where(['uid' => $userinfo['id'], 'type' => $type])->find();
            $data = [
                'account_num' => $account_num,
                'code' => $code,
                'update_time' => time(),
                'bank' => $bank,
                'account' => $userinfo['truename'],
            ];
            if (empty($info)) {
                $data['uid'] = $userinfo['id'];
                $data['type'] = $type;
                $data['time'] = time();
                $res = Db('bank')->insert($data);
            } else {
                $res = Db('bank')->where(['id' => $info['id']])->update($data);
            }
            if (!$res) {
                throw new \Exception('绑定失败');
            }
            apifasong(['zt' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            apifasong(['zt' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * @name 获取支付方式
     * @author zay
     * @Date 2020/4/7 0007 13:40
     */

    public function getpay($appdata, $userinfo)
    {
        $pay_list = Db('bank')
            ->field('id,account_num,code,account,bank,type')
            ->where(['uid' => $userinfo['id']])
            ->select();
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $pay_list]);
    }

    /**
     * @name 赠送币列表
     * @author zay
     * @Date 2020/4/8 0008 11:10
     */

    public function sendcoin($appdata, $userinfo)
    {
        $page = isset($appdata['page']) ? $appdata['page'] : 1;
        $page = $page < 1 ? 1 : $page;
        $limit = 20;
        $list = Db('invite_reward_coin')
            ->field('id,from_uname,time,coin')
            ->where(['uid' => $userinfo['id']])->order('time')
            ->limit($limit, ($page - 1) * $page)
            ->select();
        apifasong(['zt' => 1, 'msg' => '获取成功', 'data' => $list]);

    }
}